package com.pig4cloud.pig.base.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.admin.api.entity.SysDictItem;
import com.pig4cloud.pig.admin.api.feign.RemoteDictService;
import com.pig4cloud.pig.base.api.dto.LogDto;
import com.pig4cloud.pig.base.api.vo.LogVO;
import com.pig4cloud.pig.base.service.LogService;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.R;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * packageName com.pig4cloud.pig.base.service.impl
 *
 * @author marco
 * @className LogServiceImpl (此处以class为例)
 * @date 2024/5/30
 * @description TODO
 */
@Service
@AllArgsConstructor
public class LogServiceImpl implements LogService {
	@Autowired
	private RestHighLevelClient client;
	private RemoteDictService remoteDictService;
	/***
	* @Description: 分页查询日志
	* @Param: []
	* @return: Page
	* @Author: marco
	* @Date: 2024/5/30
	*/
	@Override
	public Page PageQuery(Page page, LogDto logDto) throws IOException {
		List<LogVO> logVOList=new ArrayList<>();
		SearchRequest request =new SearchRequest();
		StringBuilder index = new StringBuilder();
		SearchSourceBuilder builder = new SearchSourceBuilder();
		if(StringUtils.isNotEmpty(logDto.getService())){
			request.indices(logDto.getService()+CommonConstants.CHAR);
			BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
			// 添加must条件
			boolQueryBuilder.must(QueryBuilders.matchQuery(CommonConstants.SERVICE, logDto.getService()));
			builder.query(boolQueryBuilder);
		}else{
			R<List<SysDictItem>> dictByType = remoteDictService.getDictByType(CommonConstants.SERVICETYPE);
			if(dictByType.isSuccess()){
				dictByType.getData().forEach(sysDictItem -> {
					index.append(sysDictItem.getItemValue()+CommonConstants.CHAR);
					index.append(CommonConstants.CHAR2);
				});
			}
			request.indices(String.valueOf(index));
			builder.query(QueryBuilders.matchAllQuery());
		}
		builder.sort("@timestamp", SortOrder.DESC);
		builder.from((int) page.getCurrent());
		builder.size((int) page.getSize());
		request.source(builder);
		SearchResponse response = client.search(request, RequestOptions.DEFAULT);
		SearchHits hits = response.getHits();
		for(SearchHit hit:hits){
			System.out.println(hit.getSourceAsString());
			JSONObject jsonObject = JSONObject.parseObject(hit.getSourceAsString());
			LogVO logVO=JSON.toJavaObject(jsonObject, LogVO.class);
			//UTC 时区时间转换
			DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
			ZonedDateTime zonedDateTime = ZonedDateTime.parse(jsonObject.getString("@timestamp"), formatter);
			Date date = java.util.Date.from(zonedDateTime.toInstant());
			logVO.setTimestamp(date);
			logVOList.add(logVO);
		}
		page.setTotal(hits.getTotalHits().value);
		page.setPages(hits.getTotalHits().value/page.getSize());
		page.setRecords(logVOList);
		return page;
	}
}
